package com.wuzihao.disk.spring.security;

import com.wuzihao.disk.login.service.LoginService;
import com.wuzihao.disk.mybatis.entity.PtUserEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class GdmtUserDetailsService implements UserDetailsService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private LoginService loginService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        PtUserEntity ptUserEntity = loginService.queryUserInfoByName(username);
        if (ptUserEntity == null) {
            throw new UsernameNotFoundException("the user is not find userName:" + username);
        }

        List<String> permissionList = loginService.queryPermissionList(ptUserEntity.getUserUuid());
        List<GrantedAuthority> collection = new ArrayList<>();
        //       collection.add(new SimpleGrantedAuthority("ROLE_Test1"));
        for (String permissionItem : permissionList) {
            collection.add(new SimpleGrantedAuthority("ROLE_" + permissionItem));
        }
        // 参数分别是：用户名，密码，用户权限
        UserDiskEntity user = new UserDiskEntity(ptUserEntity, collection);

        return user;
    }
}
